<template>
    <div class="loginform-container">
        <div class="loginform-content">
            <h2>{{ t("登录") }}</h2>
            <div class="loginform-form">
                <ElForm ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="auto" :size="formSize"
                    label-position="top" status-icon>
                    <ElFormItem :label="t('账号')" prop="loginID" size="large">
                        <ElInput v-model="ruleForm.loginID" v-enter="handleLogin"></ElInput>
                    </ElFormItem>
                    <ElFormItem :label="t('密码')" prop="loginPW" size="large">
                        <ElInput v-model="ruleForm.loginPW" type="password" :show-password="true" v-enter="handleLogin">
                        </ElInput>
                    </ElFormItem>
                    <div style="display: flex;justify-content: right;padding: 10px 0 0 0; height: 30px;">
                        <!-- <a src="#">忘记密码</a> -->
                    </div>
                    <div style="display: grid;padding: 20px 5px 0 5px;">
                        <ElButton type="primary" size="large" @click="handleLogin" v-enter="handleLogin">登录</ElButton>
                    </div>
                    <!-- <div style="display: grid;padding: 10px 5px 0 5px;">
                    <ElButton>注册</ElButton>
                </div> -->
                </ElForm>
            </div>
        </div>
    </div>
</template>
<script setup lang="ts">
import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
import { ElForm, ElFormItem, ElInput, ElButton, ElMessage } from 'element-plus';
import { getCurrentInstance, reactive, ref } from 'vue';
import { t } from '@/common/locale'
import { useRouter } from 'vue-router';
import { doLogin, getMenu } from '@/api/authorization';
import { useUsers } from '@/stores';
import elHelper from '@/common/elHelper';
import ssHelper from '@/common/sessionStoreHelper'
import { ROUTER_NAV_LIST_KEY } from '@/constants';

const userStore = useUsers()
const that = getCurrentInstance()

interface RuleForm {
    loginID: string
    loginPW: string
}

const router = useRouter()
const formSize = ref<ComponentSize>('large')

const ruleForm = reactive({
    loginID: '',
    loginPW: ''
})
const rules = reactive<FormRules<RuleForm>>({
    loginID: [
        { required: true, message: t('请输入登录账号'), trigger: 'blur' }
    ],
    loginPW: [
        { required: true, message: t('请输入密码'), trigger: 'blur' }
    ]
})

const hadChild = (allRouter, current) => {
    let hadChild = false
    for (let i = 0; i < allRouter.length; i++) {
        if (allRouter[i].function_url && allRouter[i].p_function_no === current.function_no) {
            hadChild = true
            break
        }
    }
    return hadChild
}
const handleLogin = async () => {
    const form = that?.refs.ruleFormRef as FormInstance | undefined
    if (!form) return

    const validResult = await form.validate((valid) => valid)
    if (validResult) {
        const loading = elHelper.showLoading()
        const result = await doLogin(ruleForm.loginID, ruleForm.loginPW)
        if (result.isSuccess) {
            if (window.location.href.indexOf('?') > 0 && window.location.href.indexOf('?redirect') < 0) {
                let baseUrl = decodeURIComponent(window.location.href.slice(window.location.href.indexOf('?') + 1))
                if (baseUrl.indexOf('?') > -1) {
                    window.location.href = baseUrl + '&_token=' + userStore.getLoginToken()
                } else {
                    window.location.href = baseUrl + '?_token=' + userStore.getLoginToken()
                }
            } else {
                let menulist = await getMenu()
                if (menulist.length) {
                    let toUrl = ''
                    let routerNavList: any[] = []
                    for (let i = 0; i < menulist.length; i++) {
                        if (menulist[i].function_url && menulist[i].url_type === 'Router' && !hadChild(menulist, menulist[i])) {
                            toUrl = toUrl || menulist[i].function_url
                            routerNavList.push(menulist[i])
                        }
                    }
                    ssHelper.set(ROUTER_NAV_LIST_KEY, (routerNavList && routerNavList.length) ? routerNavList : '')
                    if (toUrl) {
                        router.push(toUrl)
                        return
                    } else {
                        elHelper.showWarningMsg('请检查配置的功能地址（function_url）是否正确')
                    }
                } else {
                    elHelper.showWarningMsg('该账号暂无功能权限，请联系管理员添加权限')
                }
                router.push('/dashboard/home')
            }
            elHelper.closeLoading(loading)
        } else {
            ElMessage.error(t(result.msg))
            elHelper.closeLoading(loading)
        }
    }

}
</script>
<style lang="scss" scoped>
label {
    color: #fff !important;
}

.loginform-container {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;

    .loginform-content {
        width: 100%;
        max-width: 500px;
        height: 80%;
        border: 1px solid;
        border-radius: 15px;
        border-color: var(--border-color);
        background-color: var(--login-right-bg-color);

        h2 {
            display: flex;
            justify-content: center;
            padding: 20px;
            font-size: 1.5rem;
            line-height: 2rem;
        }

        .loginform-form {
            width: 100%;
            display: flex;
            justify-content: center;

            form {
                width: 70%;
            }
        }
    }
}
</style>